package com.biwano.swapmyjob.beans;

import org.apache.commons.lang3.StringUtils;

import com.biwano.jsfextensions.converters.Validate;
import com.biwano.swapmyjob.dao.BaseDao;


public abstract class ValidatorBean extends BaseBean {
	public final String KEYSUFFIX_INVALID = "invalid";
	public final String KEYSUFFIX_MANDATORY = "mandatory";
	public final String KEYSUFFIX_UNAVAILABLE = "unavailable";
	public final String KEYSUFFIX_NOTEQUALS = "notequals";
	public final String FORMSUFFIX_INPUT = "input";
	public final String FORMSUFFIX_FORM = "form";

	public abstract String getFormId();

	public void addError(String input, String errorKey) {
		String errorfor = getFormId() + FORMSUFFIX_FORM + ":" + input
				+ FORMSUFFIX_INPUT;
		addError(errorfor, getFormId(), errorKey);
	}

	public void checkNotEmpty(String str, String inputId, String errorKey) {
		if (StringUtils.isEmpty(str))
			addError(inputId, errorKey);
	}

	public void checkMandatory(String str, String input) {
		if (StringUtils.isEmpty(str))
			addError(input, input + KEYSUFFIX_MANDATORY);
	}
	public <T> void checkAvailable(BaseDao<T> dao, Object key, String input) {
		if (dao.entityExists(key))
			addError(input, input + KEYSUFFIX_UNAVAILABLE);
	}
	public <T> void checkAvailable(BaseDao<T> dao, String param, Object key, String input) {
		if (dao.entityExists(param, key))
			addError(input, input + KEYSUFFIX_UNAVAILABLE);
	}
	public void checkEmail(String str, String input) {
		if (!Validate.eMail(str))
			addError(input, input + KEYSUFFIX_INVALID);
	}
	public void checkEquals(Object str1, Object str2, String input) {
		if (!(str1!=null && str1.equals(str2)))
		{
			addError(input, input + KEYSUFFIX_NOTEQUALS);
		}
	}

	public abstract void validateInput();

	public abstract RETURNVALUE beanAction() throws Exception;

	public void onBeanActionError() {
		onError();
	}

	public void onError() {
		addError("error", "general", "unexpected");
	}

	public String action() {
		RETURNVALUE res = RETURNVALUE.success;
		RETURNVALUE tmp = null;
		try {
			validateInput();
			if (!hasErrors())
				tmp = beanAction();
			else
				tmp = RETURNVALUE.error;
			if (tmp != null)
				res = tmp;
		} catch (BeanException e) {
			onBeanActionError();
			res = RETURNVALUE.error;
		} catch (Exception e) {
			onError();
			res = RETURNVALUE.unhandlederror;
			e.printStackTrace();
		}
		return res.toString();
	}
}
